const router = require('koa-router')()
const svgCaptcha = require('svg-captcha')
const jwt = require('jsonwebtoken');
const fs = require('fs');
const path = require('path');
var image = require("imageinfo");

// var mimeType = require('mimeType')

const myKey = 'CYJMWXK';
let imgList = [];

// const usermessage = [{
//   'username':'yuanxiaoli',
//   'userpsd':123456
// }];

const result = [];
let num;

router.get('/yanma', async (ctx, next) => {
  let captcha = svgCaptcha.create({
    height: 36, // 下面都是配置项,详细可看官网
    fontSize: 40,
    color: false,
    ignoreChars: '0oO1iIl',
    noise: 1
  })
  // console.log(captcha)
  ctx.body = captcha;
  num = captcha.text;

})

router.get('/getcount', async (ctx, next) => {
  let sql = "select * from images"
  let result = await ctx.db.EXCUTE(sql);
  // console.log(captcha)
  ctx.body = result.length;

})

router.post('/toplog',async(ctx,next)=>{
  let id = ctx.request.body.id ;
  let sql1 = `UPDATE logManager SET logTop = 1 WHERE logTop = 0 `;
  ctx.db.EXCUTE(sql1);
  let sql = `UPDATE logManager SET logTop = 0 WHERE logId = ${id} `;
  await ctx.db.EXCUTE(sql);
  // let filePath1 = path.join(__dirname, 'images/') + `${name}`;
  // fs.unlinkSync(filePath1)
  ctx.body={
    msg: '删除文件成功！'
  }
  // console.log(name);
  // ctx.body='ok';
})

router.get('/getucount',async(ctx,next) => {
  let sql = "select * from userManager"
  let result = await ctx.db.EXCUTE(sql);
  // console.log(captcha)
  ctx.body = result.length;
})

router.get('/getulcount',async(ctx,next) => {
  let sql = "select * from logManager"
  let result = await ctx.db.EXCUTE(sql);
  // console.log(captcha)
  ctx.body = result.length;
})

router.post('/deleteimg',async(ctx,next)=>{
  let id = ctx.request.body.id ;
  let sql = `delete from images where imgId = ${id}`;
  await ctx.db.EXCUTE(sql);
  // let filePath1 = path.join(__dirname, 'images/') + `${name}`;
  // fs.unlinkSync(filePath1)
  ctx.body={
    msg: '删除文件成功！'
  }
  // console.log(name);
  // ctx.body='ok';
})

router.post('/deleteuser',async(ctx,next)=>{
  // console.log(ctx);
  let id = ctx.request.body.id;
  let sql = `delete from userManager where userId = ${id}`;
  await ctx.db.EXCUTE(sql);
  // userMessage= userMessage.filter(item => item.id != id);

  ctx.body = {
    msg: '删除用户成功！'
  }
})

router.post('/deletelog',async(ctx,next)=>{
  // console.log(ctx);
  let id = ctx.request.body.id;
  let sql = `delete from logManager where logId = ${id}`;
  await ctx.db.EXCUTE(sql);
  // userMessage= userMessage.filter(item => item.id != id);
  ctx.body = {
    msg: '删除用户成功！'
  }
})

router.post('/changeuser',async(ctx,next)=>{
  var user = ctx.request.body.user;
  console.log(ctx.request.body.user);
  let sql = "select * from userManager"
  let result = await ctx.db.EXCUTE(sql);
  var count = result.length;
  result.map(item=>{
    if(item.userId == user.userId){
      let sql2 = `UPDATE userManager SET userName = '${user.userName}', userPhone = '${user.userPhone}' ,userAdress = '${user.userAdress}',useremail = '${user.useremail}' WHERE userId = ${user.userId} `;
      ctx.db.EXCUTE(sql2);
      count --;
      ctx.body = {
        msg: '修改用户信息成功！'
      }
    }
  })
  if(count==result.length){
      let sql3 = `INSERT INTO userManager (userName, userPhone, userAdress, useremail) VALUES('${user.userName}','${user.userPhone}','${user.userAdress}','${user.useremail}');`
      ctx.db.EXCUTE(sql3);
      ctx.body = {
        msg: '添加用户信息成功！'
      }
  }
})

router.post('/changelog',async(ctx,next)=>{
  var logItem = ctx.request.body.logItem;
  console.log(logItem);
  let sql = "select * from logManager"
  let result = await ctx.db.EXCUTE(sql);
  var count = result.length;
  result.map(item=>{
    if(item.logId == logItem.logId){
      let sql2 = `UPDATE logManager SET logName = '${logItem.logName}', logPhone = '${logItem.logPhone}' ,logAddress = '${logItem.logAddress}',logPath = '${logItem.logPath}' WHERE logId = ${logItem.logId} `;
      ctx.db.EXCUTE(sql2);
      count --;
      ctx.body = {
        msg: '修改用户信息成功！'
      }
    }
  })
  if(count==result.length){
      let sql3 = `INSERT INTO logManager (logName, logPhone, logAddress, logPath,logTop) VALUES('${logItem.logName}','${logItem.logPhone}','${logItem.logAddress}','${logItem.logPath}',1);`
      ctx.db.EXCUTE(sql3);
      ctx.body = {
        msg: '添加用户信息成功！'
      }
  }
})

router.post('/searchuser', async (ctx,next)=>{
  let userName = ctx.request.body.name;
  let sql = `select * from userManager where userName = '${userName}'`;
  let user = await ctx.db.EXCUTE(sql);
  ctx.body = user;
})

router.post('/searchlog', async (ctx,next)=>{
  let logName = ctx.request.body.name;
  let user;
  if(logName){
    let sql = `select * from logManager where logName like '%${logName}%' or logPath like '%${logName}%' or logAddress like '%${logName}%' or logPhone like '%${logName}%'`;
    user = await ctx.db.EXCUTE(sql);
  }else{
    user = [];
  }
  
  
  ctx.body = user;
})

router.post('/login', async (ctx, next) => {
  const content = ctx.request.body;
  console.log(content);
  let sql = `select * from manager`;
  let usermessage = await ctx.db.EXCUTE(sql);
  usermessage.map((index)=>{
    console.log(index);
    if(index.username == content.username && index.userpsd == content.userpwd && num == content.yanma){
      let token = jwt.sign({"userName":content.username},myKey);
      // // console.log(token);
      ctx.body = {token:token,status:'ok'};
      // ctx.body='ok';
    }
  }) 
})

router.post('/uploadimg', async (ctx, next) => {
  let file = ctx.request.files.file;
  let token = ctx.request.headers.authorization;
  let result = jwt.verify(token,myKey);
  if(result.userName){
    const reader = fs.createReadStream(file.filepath);
    let filename = file.originalFilename;
    let listPath = path.join(__dirname, 'images/');
    let filePath = listPath + `${filename}`;
    let upStream = fs.createWriteStream(filePath);
    reader.pipe(upStream);
    console.log(file);
    var imgpath = 'http://localhost:3000/'+ file.originalFilename;
    let sql = `INSERT INTO images (imgName, imgType, imgSize, imgPath) VALUES('${file.originalFilename}','${file.mimeType}','${file.size}','${imgpath}');`
    await ctx.db.EXCUTE(sql);
    ctx.body = {'status':'success'};
  }
})

router.post('/getimg',async(ctx,next)=>{
  let page = ctx.request.body.page;
  // let listPath = path.join(__dirname, './images/') ;
  // var files = fs.readdirSync(listPath);
  // files.forEach(function (itm, index) {
  //   var stat = fs.statSync(listPath + itm);
  //   var ms = image(fs.readFileSync(listPath + itm));  
  //   var obj = {};//定义一个对象存放文件的路径和名字
  //   obj.path = 'http://localhost:3000/'+itm;//路径
  //   obj.filename = itm;//名字
  //   obj.filesize = stat.size;
  //   obj.filetype = ms.mimeType;
  //   imgList.push(obj);
  // })
  // console.log(imgList.length);
  let sql = "select * from images"
  let imgList = await ctx.db.EXCUTE(sql);
  if(imgList.length>=10*(page-1)){
    var newList = imgList.slice(10*(page-1),10*page);
    // console.log(newList);
    ctx.body = newList;
  }else{
    ctx.body = [];
  }
})

router.post("/getuser",async(ctx,next)=>{
  let page = ctx.request.body.page;
  let sql = "select * from userManager"
  let result = await ctx.db.EXCUTE(sql);
  // console.log(result);
  if(result.length>=10*(page-1)){
    var newList = result.slice(10*(page-1),10*page);
    // console.log(newList);
    ctx.body = newList;
  }else{
    ctx.body = [];
  }
})

router.post("/getlogistics",async(ctx,next)=>{
  let page = ctx.request.body.page;
  let sql = "select * from logManager order by logTop ASC"
  let result = await ctx.db.EXCUTE(sql);
  // console.log(result);
  if(result.length>=5*(page-1)){
    var newList = result.slice(5*(page-1),5*page);
    // console.log(newList);
    ctx.body = newList;
  }else{
    ctx.body = [];
  }
})

module.exports = router
